import sys
import tkinter as tk
from tkinter import messagebox
import requests
from datetime import datetime

def get_remaining_calories(machine_id, target_calories):
    # 这里应该有获取当前已消耗卡路里数据的逻辑
    # 为了演示，假设已消耗了100卡路里
    consumed_calories = 100
    remaining_calories = target_calories - consumed_calories
    return max(remaining_calories, 0)

def get_remaining_distance(machine_id, target_distance):
    # 这里应该有获取当前已行走距离数据的逻辑
    # 为了演示，假设已走了50米
    walked_distance = 50
    remaining_distance = target_distance - walked_distance
    return max(remaining_distance, 0)

def upload_data(url, data):
    try:
        response = requests.post(url, json=data)
        if response.status_code == 200:
            return response.json()
        else:
            messagebox.showerror("错误", f"请求失败: {response.status_code}")
            return None
    except Exception as e:
        messagebox.showerror("错误", f"请求时出错: {e}")
        return None

def on_calories_button_click():
    try:
        current_time = datetime.now().strftime('%Y%m%d%H%M%S')
        data = {
            "time": current_time,
            "machine_id": machine_id
        }
        response_data = upload_data("http://47.108.221.119:5000/getRemainingCalories", data)
        if response_data:
            result_calories.set(f"剩余卡路里: {response_data.get('data')}")
    except Exception as e:
        messagebox.showerror("错误", f"计算或上传剩余卡路里时出错: {e}")

def on_distance_button_click():
    try:
        current_time = datetime.now().strftime('%Y%m%d%H%M%S')
        data = {
            "time": current_time,
            "machine_id": machine_id
        }
        response_data = upload_data("http://47.108.221.119:5000/getRemainingDistance", data)
        if response_data:
            result_distance.set(f"剩余距离: {response_data.get('data')}")
    except Exception as e:
        messagebox.showerror("错误", f"计算或上传剩余距离时出错: {e}")

machine_id = sys.argv[1] if len(sys.argv) > 1 else "未提供机器码"

# 创建主窗口
root = tk.Tk()
root.title(f"机器 {machine_id} 的目标剩余")

result_calories = tk.StringVar()
result_distance = tk.StringVar()

tk.Button(root, text="获取剩余卡路里", command=on_calories_button_click).pack(pady=5)
tk.Label(root, textvariable=result_calories).pack(pady=5)

tk.Button(root, text="获取剩余距离", command=on_distance_button_click).pack(pady=5)
tk.Label(root, textvariable=result_distance).pack(pady=5)

root.mainloop()